package com.itheima.bigevents.interceptions;

import com.itheima.bigevents.utils.JwtUtil;
import com.itheima.bigevents.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;


//拦截器
@Component //将Bean对象注册到Spring ioc容器中
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        //验证token
        try {
            //解析token
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //存数据到ThreadLocalUtil
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            //token验证失败状态码为401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            //response.sendRedirect("/login");
            //返回false，拦截请求
            return false;
        }



//
//        Object user = request.getSession().getAttribute("user");
//        if(user == null){
//            //未登录，重定向到登录页面
//            response.sendRedirect("/login");
//            return false;
//        }
//        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除ThreadLocalUtil中的数据
        ThreadLocalUtil.remove();
    }

}
